import { Component, Input, Output, EventEmitter, OnInit, OnChanges } from '@angular/core';
import { NzNotificationService } from 'ng-zorro-antd';
import { HttpServcie } from '../../../service/http.service';
import { UsedPartyDetailBean } from '../bean/usedPartyDetail.bean';
import { el } from "@angular/platform-browser/testing/src/browser_util";
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
import { NoticeBean } from '../bean/notice.bean';
import { Observable } from 'rxjs/Rx';
import {FileUploader,FileItem,ParsedResponseHeaders} from  'ng2-file-upload';
import { Config } from '../../../service/config';
import * as moment from 'moment';
import { NzModalService, NzModalSubject } from 'ng-zorro-antd';
@Component({
    selector: 'used-party-detail',
    templateUrl: './used-party-detail.html',
    styleUrls: ['./used-party-detail.scss']
})
export class UsedPartyDetailPage implements OnInit, OnChanges {
    @Input() inValue: string;
    @Output("outPut") outPut = new EventEmitter();
    validateForm: FormGroup;
    isSpinning: boolean = false;
    inPartyId: string;
    expandDataCache = {};
    data = [];
    config = Config;
    isDisable = false;
    showImage: any = [];
    hasAdd = false;
    showImage1 = [];
    picList= [];
     fileUploader = new FileUploader({
        url: Config.IP+Config.API.upload,
        method: "POST",
        itemAlias: "file",
        autoUpload: false,
        headers:[
            {name:"Authorization",value:'Bearer ' + window.localStorage['token']}
        ]
    });
    usedPartyDetailBean: UsedPartyDetailBean = new UsedPartyDetailBean();
    noticeBean: NoticeBean = new NoticeBean();
    constructor(
        private fb: FormBuilder,
        private httpServcie: HttpServcie,
        private _notification: NzNotificationService,
        private nsub: NzModalSubject,
        private modalService: NzModalService
    ) {
        this.usedPartyDetailBean.partyId = JSON.parse(window.localStorage['user']).partyId;
        if(this.inPartyId){
            this.usedPartyDetailBean.partyId = this.inPartyId;
        }
        this.httpServcie.queryUsedDetail({ id: this.usedPartyDetailBean.partyId }).subscribe((data) => {
            if(data.data!=null){
                this.usedPartyDetailBean = data.data;
                if(this.usedPartyDetailBean.zzsUrl){
                    this.showImage1=this.usedPartyDetailBean.zzsUrl.split(',');
                }
            }
            
        });
    }

    ngOnInit() {
        this.validateForm = this.fb.group({
            partyId: [null, [Validators.required]],
            businessScope: [null, [Validators.required]],
            elevatorNum: [null, [Validators.required]],
            operatorNum: [null, [Validators.required]],
            specialEquipmentAccidents: [[], [Validators.required]],
            legalPersonName: [null, [Validators.required]],
            legalPersonPhone: [null, [Validators.required]],
            safetyPersonName: [null, [Validators.required]],
            zzjb: [null, [Validators.required]],
            czryNum: [null, [Validators.required]],
            safetyPersonPhone:[null, [Validators.required]],
        });
    }
    ngOnChanges() {
        this.inPartyId = '';
        if (this.inValue) {
            this.isDisable = true;
            this.inPartyId = this.inValue;
            this.usedPartyDetailBean.partyId = this.inPartyId;
            this.httpServcie.queryUsedDetail({ id: this.usedPartyDetailBean.partyId }).subscribe((data) => {
                if(data.data!=null){
                    this.usedPartyDetailBean = data.data;
                    if(this.usedPartyDetailBean.zzsUrl){
                        this.showImage1=this.usedPartyDetailBean.zzsUrl.split(',');
                    }
                }else{
                    this.usedPartyDetailBean = new UsedPartyDetailBean();
                    this.usedPartyDetailBean.partyId = this.inPartyId;

                }
                
            })
        }
    }
    submitForm() {
        this.isSpinning = true;
        if(this.showImage1){
            this.usedPartyDetailBean.zzsUrl = this.showImage1.join(',');
        }
        
        if (this.usedPartyDetailBean.id) {
            this.httpServcie.updateUsedDetail(this.usedPartyDetailBean).subscribe((data) => {
                console.log(data);
                this.isSpinning = false;
                this._notification.create('success', '提示', '修改成功！');
            });
        } else {
            if(this.hasAdd){
                this.isSpinning = false;
                this._notification.create('warning', '提示', '已经新增完成，如要修改请重新打开！');
                return;
            }
            this.httpServcie.addUsedDetail(this.usedPartyDetailBean).subscribe((data) => {
                this.hasAdd = true
                this.isSpinning = false;
                this._notification.create('success', '提示', '新增成功！');
            })
        }

    }
    //交验
    getFormControl(name) {
        return this.validateForm.controls[name];
    }

    selectedFileOnChanged(event){
        if(event.target.files[0].type.match('image.*')){
            //手动上传的
            this.fileUploader.uploadAll();
            this.fileUploader.onSuccessItem =(item: FileItem, response: string, status: number, headers: ParsedResponseHeaders)=>{
                    if(status==200){
                        //判断是否是图片
                        if(item.file.type.match('image.*')){
                            this.showImage.push(JSON.parse(response).data);
                            //this.userBean.qualificationsUrl = JSON.parse(response).data;
                        }else{
                            this._notification.create('warning', '警告提示', '请选择图片类型！');
                        }
                    }
            }
        }else {
            this.fileUploader.clearQueue();
            this._notification.create('warning', '警告提示', '请选择图片类型！');
        }
    }

    delete(param){
        this.httpServcie.deleteUpload(param).subscribe(data=>{
            if(data.status==200){
                this.httpServcie.removeByValue(this.showImage,param);
                //this._notification.create('success', '成功提示', '移除成功');
            }else{
                //this._notification.create('error', '失败提示', data.message);
                return;
            }
        },error=>{

        });
    }

    sendMessage(){
        let noticeTime = moment(new Date()).format('YYYYMMDDHHmmss');
        this.noticeBean.noticeTime = noticeTime;
        this.noticeBean.sendUserId = JSON.parse(window.localStorage.getItem('user')).id;
        this.noticeBean.fileUrls = this.showImage.join(',');
        this.noticeBean.receivePartyId = this.inPartyId;
        this.noticeBean.isRead = '0';
        this.httpServcie.sendNotice(this.noticeBean).subscribe((data)=>{
            if(data.status=200){
                this._notification.create('success', '提示', '通知成功');
            }else{
                this._notification.create('error', '提示', data.message);
            }
        })

    }

    //选择文件后调用的方法
    selectedFileOnChanged1(event){
        if(event.target.files[0].type.match('image.*')){
            //手动上传的
            this.fileUploader.uploadAll();
            this.fileUploader.onSuccessItem =(item: FileItem, response: string, status: number, headers: ParsedResponseHeaders)=>{
                    if(status==200){
                        //判断是否是图片
                        if(item.file.type.match('image.*')){
                            this.showImage1.push(JSON.parse(response).data);
                            //this.userBean.qualificationsUrl = JSON.parse(response).data;
                        }else{
                            this._notification.create('warning', '警告提示', '请选择图片类型！');
                        }
                    }
            }
        }else {
            this.fileUploader.clearQueue();
            this._notification.create('warning', '警告提示', '请选择图片类型！');
        }
    }

    delete1(param){
        this.httpServcie.deleteUpload(param).subscribe(data=>{
            if(data.status==200){
                this.httpServcie.removeByValue(this.showImage1,param);
                //this._notification.create('success', '成功提示', '移除成功');
            }else{
                //this._notification.create('error', '失败提示', data.message);
                return;
            }
        },error=>{

        });
    }


    showlargeImg(titlepic, contentpic, footerpic, param){
        this.picList=[];
        this.picList.push(param);
        this.modalService.open({
        title       : titlepic,
        content     : contentpic,
        footer      : footerpic,
        maskClosable: false,
        width:800,
        zIndex:9999,
        style : {
            top: '20px'
        },
        onOk() {
            console.log('Click ok');
        }
        });
      }
        
}
